import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import md5 from 'js-md5'

var getId = () => {
  return localStorage.getItem('userId');
}

var getToken = () => {
  return localStorage.getItem('token');
}

var showErr = true

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const baseURL = process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_URL_PROD : process.env.VUE_APP_BASE_URL_DEV;

const service = axios.create({
  baseURL,
  timeout: 10000
});

// request拦截器
service.interceptors.request.use(config => {
  if (config && config.data && 'showErr' in config.data) {
    showErr = config.data.showErr
  }

  if (config.method === 'post' && !config.data) {
    config.data = {}
    config.data.aid = getId()
    config.data.t = new Date().getTime()
  } else if (config.method === 'post' && config.data) {
    config.data.aid = getId()
    config.data.t = new Date().getTime()
  }

  if (config.method === 'post') {
    config.transformRequest = (data, headers) => {
      let req = JSON.stringify(data)
      let token = getToken()
      let sign = md5(req + token)
      console.log(req + token)
      config.headers['sign'] = sign
      return req
    }
  }


  if (config.method === 'get' && !config.params) {
    config.params = {}
    config.params.accessToken = getToken()
    config.params.timeStamp = new Date().getTime()
  } else if (config.method === 'get' && config.params) {
    if (!config.params.accessToken) config.params.accessToken = getToken()
    config.params.timeStamp = new Date().getTime()
  }

  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof (value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            if (value[key] !== null && typeof (value[key]) !== 'undefined') {
              let params = propName + '[' + key + ']';
              let subPart = encodeURIComponent(params) + '=';
              url += subPart + encodeURIComponent(value[key]) + '&';
            }
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  // 未设置状态码则默认成功状态
  const code = res.data.code;
  // 获取错误信息
  //const msg = i18n.t(`errCode.E${code}`)
  const msg = res.data.msg
  const flag = res.data.flag
  if (!flag && (code === 401 || code === 403)) {
    MessageBox.confirm(msg, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
    ).then(() => {
      store.dispatch('LogOut').then(() => {
        this.$router.go(0)
      })
    }).catch(() => { });
    return Promise.reject('登录已过期，请重新登陆')
  } else if (!flag) {
    if (showErr) {
      Message({
        message: msg,
        type: 'error'
      })
    }
    return Promise.reject(new Error(msg))
  } else {
    return res.data
  }
},
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = '网络错误';
    }
    else if (message.includes("timeout")) {
      message = '服务器连接超时';
    }
    else if (message.includes("Request failed with status code")) {
      message = '网络错误' + message.substr(message.length - 3);
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
service.version = 'v1'

export default service


